package com.woniu.interceptor;



import com.woniu.util.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println("请求的路径是：" + requestURI);


        //跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        //这句话不能少，否则跨域会出现问题
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        //得到请求头中的token
        String token = request.getHeader("authentication");
        System.out.println("前端得到的token: " + token);
        if (token == null) {
            //没有token，说明没有登录
            response.getWriter().print("login,first");
        } else {
            try {
                jwtUtil.parseToken(token);
                return true;
            } catch (ExpiredJwtException e) {
                e.printStackTrace();
                throw new ExpiredJwtException(null, null, "对不起，token过期了!", e);
            } catch (SignatureException e) {
                e.printStackTrace();
                throw new SignatureException("token 错误!", e);
            } catch (RuntimeException e) {
                e.printStackTrace();
                throw new RuntimeException("token 解析出现异常!", e);
            }
        }
        return false;
    }
}
